package com.xsoft.demo10;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class TabRecyclerAdapter extends RecyclerView.Adapter<TabRecyclerAdapter.ItemViewHolder> {
    private List<TabInfo> datas;
    private int position;

    public TabRecyclerAdapter() {

    }

    public void bindData(List<TabInfo> datas) {
        this.datas = datas;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new TabRecyclerAdapter.ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_tab, null));
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, final int position) {
        if (this.position != position) {
            datas.get(position).setSelected(false);
        }
        holder.bindData(datas.get(position), new OnTabClickListener() {
            @Override
            public void onTabClick() {
                TabRecyclerAdapter.this.position = position;
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView title;
        private TabInfo info;
        private OnTabClickListener listener;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            itemView.setOnClickListener(this);
        }

        public void bindData(TabInfo info, OnTabClickListener listener) {
            this.info = info;
            title.setText(info.getTitle());
            title.setSelected(info.isSelected());
            this.listener = listener;
        }

        @Override
        public void onClick(View v) {
            info.setSelected(!info.isSelected());
            listener.onTabClick();
        }
    }

    public interface OnTabClickListener {
        void onTabClick();
    }
}
